import { useLocalStorage } from '@/use/useLocalStorage'
import axios from 'axios'
import { showDialog } from 'vant'

const instance = axios.create({
  baseURL: 'https://sysgamer.com',
  // baseURL: process.env.VUE_APP_API_URL,
})

instance.interceptors.request.use((config) => {
  const { value: token } = useLocalStorage('token', '')
  const { value: userInfo } = useLocalStorage('userInfo', '')

  if (config.headers && token.value && config.data?.header != 'none') {
    config.headers['token'] = token.value
    config.headers['user-id'] = userInfo.value.user_id
  }
  return config
})

instance.interceptors.response.use(
  (response) => {
    const { data: _data } = response
    let { data, message, error, code } = _data
    if (typeof data == 'string') {
      data = JSON.parse(data)
    }

    if (code !== 200) {
      ElMessage({
        message: error ? 'api' + error : 'API' + '_ERR',
        type: 'warning',
      })
      console.log(error ? error : 'API' + '_ERR')

      return Promise.reject({ error: error, code: code })
    }

    return data
  },
  (err) => {
    console.log(err.response)
    const { data: _data } = err.response
    let { data, message, error } = _data

    if (message !== 'success') {
      ElMessage({
        message: error ? error : 'API' + '_ERR',
        type: 'warning',
      })

      // showDialog({
      //   message: error ? 'api' + error : 'API' + '_ERR',
      // }).then(() => {
      //   // 关闭弹窗的逻辑
      // })
      return Promise.reject(message)
    }
    if (err.response && err.response.status === 401) {
      showDialog({
        message: '请登录',
      }).then(() => {
        // 关闭弹窗的逻辑
      })
    }
  }
)

export default instance
